package com.pq.controller;

import com.pq.pojo.user.User;
import com.pq.service.user.UserService;
import com.pq.utils.ObjectMapperUtil;
import com.pq.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Jedis jedis;

    @RequestMapping("/dologin")
    @ResponseBody
    public SysResult doFindLogin(String userName, String userPassword,
                              Model model, HttpServletResponse response){

        User user=userService.doLoginFind(userName,userPassword);
        if (user==null){
            return SysResult.fail();
        }
        model.addAttribute("username",userName);
        String ticket = UUID.randomUUID().toString().replace("-", "");
        // 脱敏
        user.setUserPassword("123456");
        user.setUserName(userName);
        String userJSON = ObjectMapperUtil.toJSON(user);
        // 将用户信息保存进redis中
        jedis.setex(ticket, 24*60*60, userJSON);
        // 将数据保存到Cookie中
        Cookie cookie = new Cookie("PQ_TICKET", ticket);
        cookie.setPath("/");
        cookie.setMaxAge(24*60*60);
        cookie.setDomain("pq.com");
        response.addCookie(cookie);
        return SysResult.success();
    }
    @RequestMapping("/doRegit")
    @ResponseBody
    public SysResult doFindRegit(String userName, String userPhone, String userPassword,Model model){
        User user=userService.getUserName(userName);
        userPhone=userName;
        if (user!=null){
            System.out.println(SysResult.fail());
            return SysResult.fail();
        }
        userService.doRegister(userName,userPhone,userPassword);
        System.out.println(SysResult.success());
        return SysResult.success();
    }
}
